import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter_study/review/redux/user_state.dart';
import 'package:redux/redux.dart';

void main() {
  // 创建Store
  final store =
      Store<UserState>(getReducer, initialState: UserState.initState());

  runApp(MyApp(store));
}

class MyApp extends StatelessWidget {
  final Store<UserState> _store;

  MyApp(this._store);

  @override
  Widget build(BuildContext context) {
    return StoreProvider(
      store: _store,
      child: MaterialApp(
        title: 'Redux review',
        home: FirstReduxPage(),
      ),
    );
  }
}

// 一级子页面，使用StoreBuilder
class FirstReduxPage extends StatefulWidget {
  const FirstReduxPage({Key key}) : super(key: key);

  @override
  _FirstReduxPageState createState() => _FirstReduxPageState();
}

class _FirstReduxPageState extends State<FirstReduxPage> {
  @override
  Widget build(BuildContext context) {
    return StoreBuilder<UserState>(builder: (ctx, vm) {
      return Scaffold(
        appBar: AppBar(
          title: Text('redux first page'),
        ),
        body: Center(
          child: Column(
            children: [
              Text("${vm.state.name}"),
              SizedBox(
                height: 20,
              ),
              ElevatedButton(
                  onPressed: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (ctx) => ReduxSecondPage()));
                  },
                  child: Text('next')),
            ],
          ),
        ),
      );
    });
  }
}

// 二级页面,使用StoreConnector实现，多一个converter转换函数
class ReduxSecondPage extends StatefulWidget {
  const ReduxSecondPage({Key key}) : super(key: key);

  @override
  _ReduxSecondPageState createState() => _ReduxSecondPageState();
}

class _ReduxSecondPageState extends State<ReduxSecondPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('redux second page'),
        ),
        body: StoreConnector<UserState, String>(
          builder: (ctx, name) {
            return Center(
              child: Text(name),
            );
          },
          converter: (store) => store.state.name,
        ),
        floatingActionButton:
            StoreConnector<UserState, VoidCallback>(builder: (ctx, callback) {
          return FloatingActionButton(
            child: Icon(Icons.rotate_right),
            onPressed: callback,
          );
        }, converter: (store) {
          return () => store.dispatch(UserAction.Change);
        }));
  }
}
